package day05;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/4/14
 */
public class Swap {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] num = new int[10];

        System.out.println("请输入10个整数");
        for (int i = 0; i < 10; i++) {
            System.out.print("请输入第" + (i + 1) + "个整数: ");
            num[i] = sc.nextInt();
        }

        System.out.print("请输入一个数组索引(0-9): ");
        int index = sc.nextInt();

        System.out.println("交换前数组为：");
        System.out.println(Arrays.toString(num));

        swap(num,index);

        System.out.println("交换后数组为:");
        System.out.println(Arrays.toString(num));
    }

    public static void swap(int[] num,int index) {
        // 检查索引是否有效，无效则随机生成
        if (index < 0 || index > 9) {
            Random random = new Random();
            index = random.nextInt(10);
            System.out.println("输入的索引无效，已随机生成索引: " + index);
        }

        // 不是第一个也不是最后一个
        if (index > 0 && index < 9) {
            int temp = num[index - 1];
            num[index - 1] = num[index + 1];
            num[index + 1] = temp;
        } else {
            System.out.println("索引位于数组两端，不做任何操作");
        }

    }
}
